package com.vc.activity;


import com.vc.core.VcCamera;
import com.vc.core.VcConstants;
import com.vc.core.VideoController;
import com.vc.opengl.GLRender;
import com.vc.opengl.GLRender.GLRenderListener;
import com.vc.opengl.GLView;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.OrientationEventListener;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class VideoActivity extends BaseActivity implements OnClickListener{
	
	static String TAG = "VideoActivity";
	
	VcCamera myCamera;//摄像头，属于遥控器内的一个成员

	int mCameraNum = 0;//摄像头个数，用于是否展现切换镜头按钮
	
	VideoController myController;//遥控器，里面包括摄像头实例，操作事件，回调事件
	
	SurfaceHolderListener mSurfaceHolderListener;//本地视频holder监听器

	public AudioManager mAudioManager = null;//声音管理器
	
	GLRenderListener glRenderListener;//视频监听器
	
	GLRender glRender = null;//视频渲染器
	
	public int mSdk_version;//SDK版本，用于检测SDK版本

	static final int REF_VIDEOSIZE = 960;
	
	boolean mSurfaceCreated = false;
	
	int nInFPS = 10;//帧数，初始化为10，根据硬件信息获取

	int mScreenWidth = 0;//屏幕宽高，本地视频的大小
	int mScreenHeight = 0;
	
    //int VideoWidth=240;//发送视频宽度
    //int VideoHeight=320;//发送视频高度

	boolean mReceive;//是回复还是发起
	String fromName;//发起者名字
	long myAccount;//我的帐号
	long toAccount;//对方帐号
	
    Button button_stop;//停止按钮
    Button button_switch_camera;//切换前后相机
    Button button_audio;//切换至语音聊天，视频会暂停
    Button button_video;//切换至视频聊天，视频会继续
    Button button_pause_audio;//关闭声音，限视频场景下
    Button button_resume_audio;//打开声音，限视频场景下
    
	RelativeLayout mControlLayout = null;
	

	public int mOrientation = 0;//当前屏幕方向，0,90,180,270，本用于控制文字消息框，目前没用到
	OrientationEventListener orientationListener = null;//屏幕方向监听器
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		
		//对方昵称，是接收请求还是发起请求
		fromName = super.getIntent().getStringExtra("name");
		mReceive = super.getIntent().getBooleanExtra("receive", true);
		toAccount = super.getIntent().getLongExtra("toAccount",0);

		//注册一个广播接收器
		IntentFilter intentFilter = new IntentFilter();
	    intentFilter.addAction(VcConstants.ACTION_VIDEO_MSG);//拦截哪些广播，此处只拦截视频的广播
		this.registerReceiver(videoMsgReceiver, intentFilter);
		
		//取屏幕宽高
		mScreenWidth = getSceenWidth(getApplicationContext());
		mScreenHeight = getSceenHeight(getApplicationContext());
		
		//设置为满屏并保持屏幕常亮
		super.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
		super.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		super.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		
		setContentView(R.layout.videochat);

		//控制层
		mControlLayout = (RelativeLayout) findViewById(R.id.sharp_control_RelativeLayout);
		
		//取SDK版本
		mSdk_version = android.os.Build.VERSION.SDK_INT;
		
		//获取遥控器
		myController = VideoController.getInstance();
		myController.setAppRuntime(this.getApplication());//TODO 基于性能考虑，此处需改为全局application
		
		//发送一个获取网关IP请求
		myController.sendGetGatewayIpReq();
		
		//TODO 测试，待删除，发广播示例
		//myController.sendVideoMsgBroadcast(VcConstants.TYPE_CONNECT_FAILED);		
		
		//获取摄像头实例
		myCamera = myController.getVcCamera();
		
		//摄像头初始化失败，直接结束
		if (myCamera == null) {
			Log.e(TAG, "Create video failed because camera open failed.");
			super.finish();
			return;
		}
		
		//获取摄像头个数
		mCameraNum = myCamera.GetNumberOfCamera();
	
		//是否已暂停视频
		myController.mPauseVideo = false;
		
		//初始化播放窗口
		initRemoteSurfaceView();
		
		//初始化视频录制窗口
		initLocalSurfaceView();

		//注册屏幕方向监听器
		registerOrientationListener();
		
		int result = -1;
		
		//接受 还是 发起
		if(mReceive){
			//接受了视频请求
			result = myController.acceptedVideoChat(myAccount);
			//startFinishTimer();//做个3秒的延迟
		}else{
			//发起视频请求，主叫是会默认把摄像头打开的，一旦通道建立成功就直接发视频音频数据给对方了
			result = myController.requestVideoChat(toAccount);
			//TODO 显示呼叫的UI
		}
		
		//视频请求/应答失败
		if (result != 0) {
			Log.e(TAG, "Video connect fail!");
			super.finish();
			return;
		}
		
		//声音控制器
		mAudioManager = (AudioManager)super.getSystemService(Context.AUDIO_SERVICE);
		
		//初始化控制按钮
		button_stop = (Button)findViewById(R.id.button_stop);
		button_switch_camera = (Button)findViewById(R.id.button_switch_camera);
		button_pause_audio = (Button)findViewById(R.id.button_pause_audio);
		button_resume_audio = (Button)findViewById(R.id.button_resume_audio);
		button_audio = (Button)findViewById(R.id.button_audio);
		button_video = (Button)findViewById(R.id.button_video);
		button_audio.setOnClickListener(this);
		button_video.setOnClickListener(this);
		button_pause_audio.setOnClickListener(this);
		button_resume_audio.setOnClickListener(this);
		button_switch_camera.setOnClickListener(this);
		button_stop.setOnClickListener(this);
	}
	
	/**
	 * 切换镜头在新线程中
	 * @author Administrator
	 *
	 */
	class SwitchCameraRunnable implements Runnable {
		@Override
		public void run() {
			boolean result = myCamera.switchCamera();
			if (result) {
				SurfaceView localVideo = (SurfaceView) findViewById(R.id.sharp_video_surfaceview);
				SurfaceHolder holder = localVideo.getHolder();
				holder.addCallback(mSurfaceHolderListener);
				myCamera.startCamera(holder);
			}			
		}
	}
	
	/**
	 * 本地视频Surface的Holder
	 */
	class SurfaceHolderListener implements SurfaceHolder.Callback{
		
		@Override
		public void surfaceCreated(SurfaceHolder holder) {
			//locateCameraPreview();
			VideoActivity.this.mSurfaceCreated = true;
			if (myController != null && !myController.mPauseVideo) {
				if (myCamera!=null && !myCamera.isCameraOpened()) {
					Runnable runnable = new StartCameraRunnable(holder);
					myController.execute(runnable);
				}
			}						
		}
        
		@Override
		public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {			
			if (holder.getSurface() == null) {
		        return;
		    }
			holder.setFixedSize(width, height);
		}

		@Override
		public void surfaceDestroyed(SurfaceHolder holder) {			
			mSurfaceCreated = false;
		}
		
        class StartCameraRunnable implements Runnable {
            SurfaceHolder mSurfaceHolder;
            public StartCameraRunnable(SurfaceHolder holder) {
                this.mSurfaceHolder = holder;
            }
			@Override
            public void run() {
            	myCamera.startCamera(mSurfaceHolder);
            }
        }
	}
  
  
	/**
	 * 播放的渲染器监听器，暂时不用监听
	 */
	public class GLRenderListener_impl implements GLRender.GLRenderListener{
		
	    public void onRenderCreated(GLRender r)
	    {
	    	Log.d(TAG, "GLRenderListener_impl.onRenderCreated");
//	    	if(myController!=null){
//		    	myController.setPeerGLRenderer(r);
//	    		r.requestRender();
//    		}
	    }

	    public void onRenderDestroyed(GLRender r)
	    {
	    	Log.d(TAG, "GLRenderListener_impl.onRenderDestroyed");
//	    	if(myController!=null){
//	    		myController.setPeerGLRenderer(null);
//	    	}
	    }

	    public void onRenderInfoNotify(GLRender r, int w, int h, int angle)
	    {
	    	Log.d(TAG, "GLRenderListener_impl.onRenderInfoNotify");
	    }
    }
	
	/**
	 * 广播通知器
	 * @author Administrator
	 *
	 */
    private BroadcastReceiver videoMsgReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
        	Log.d(TAG, "videoMsgReceiver|action="+intent.getAction());
            if (intent.getAction().equals(VcConstants.ACTION_VIDEO_MSG)) {
                int type = intent.getIntExtra("type", VcConstants.TYPE_ERROR);
            	Log.d(TAG, "videoMsgReceiver|type="+type);
                switch(type){
                	case VcConstants.TYPE_CONNECT_FAILED:
                		Toast.makeText(context, "测试广播", Toast.LENGTH_LONG);
                		//TODO 视频请求或应答失败
                		break;
                	case VcConstants.TYPE_FRIEND_CANCEL_REQUEST:
                		//TODO 对方取消了请求
                		break;
                	case VcConstants.TYPE_NETWORK_ERRO:
                		//TODO 网络出错或中断了
                		break;
                	case VcConstants.TYPE_CLOSED_BY_FRIEND:
                		//TODO 对方关闭了视频
                	default:
                }
            }
        }
    };
	
	/**
	 * 初始化录制用surfaceView
	 */
	private void initLocalSurfaceView() {
		Log.d("onlinechen", "initCameraPreview...");
		this.mSurfaceHolderListener = new SurfaceHolderListener();
		SurfaceView localVideo = (SurfaceView) findViewById(R.id.sharp_video_surfaceview);
	    SurfaceHolder holder = localVideo.getHolder();
	    holder.addCallback(this.mSurfaceHolderListener);
	    holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);//3.0以下必须在初始化时调用，否则不能启动预览
	    /*
		 * 关于SurfaceHolder的setType()方法的参数：
			SURFACE_TYPE_NORMAL：用RAM缓存原生数据的普通Surface
			SURFACE_TYPE_HARDWARE：适用于DMA(Direct memory access )引擎和硬件加速的Surface
			SURFACE_TYPE_GPU：适用于GPU加速的Surface
			SURFACE_TYPE_PUSH_BUFFERS：表明该Surface不包含原生数据，Surface用到的数据由其他对象提供，在Camera图像预览中就使用该类型的Surface，有Camera 负责提供给预览Surface数据，这样图像预览会比较流畅。如果设置这种类型则就不能调用lockCanvas来获取Canvas对象了。
			*/
	    localVideo.setZOrderMediaOverlay(true);
	    localVideo.setZOrderOnTop(true);//设置在顶部显示
	}
	
	
	/**
	 * 初始化播放用glSurfaceView
	 */
	private void initRemoteSurfaceView(){
		GLView bigSurfaceView = (GLView) findViewById(R.id.video_surfaceview);
		this.glRenderListener = new GLRenderListener_impl();
		this.glRender = new GLRender(bigSurfaceView,this.glRenderListener);
		bigSurfaceView.setRenderer(this.glRender);
		//setRenderMode自动or手动，手动的情况下只有触发requestRender才会渲染，性能优越
		bigSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
		//bigSurfaceView.setZOrderMediaOverlay(true);
	}
	
	
	private void locateCameraPreview() {
		Log.d(TAG, "move camera surfaceview");
		SurfaceView localVideo = (SurfaceView) findViewById(R.id.sharp_video_surfaceview);
		MarginLayoutParams params = (MarginLayoutParams) localVideo.getLayoutParams();
		params.leftMargin = -3000 * getSceenWidth(getApplicationContext()) / REF_VIDEOSIZE;
		localVideo.setLayoutParams(params);
	}
	
	/**
	 * 获取屏幕宽度，px像素单位
	 * @param c
	 * @return
	 */
	static public int getSceenWidth(Context c){
		DisplayMetrics dm = c.getResources().getDisplayMetrics();
        return dm.widthPixels;
	}
	
	/**
	 * 获取屏幕高度，px像素单位
	 * @param c
	 * @return
	 */
	static public int getSceenHeight(Context c){
		DisplayMetrics dm = c.getResources().getDisplayMetrics();
        return dm.heightPixels;
	}
	
	/**
	 * 屏幕方向监听器
	 * @author Administrator
	 *
	 */
	class MsgBoxOrientationEventListener extends OrientationEventListener {
		
		public MsgBoxOrientationEventListener(Context context, int rate) {
			super(context, rate);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void onOrientationChanged(int orientation) {
			Log.d(TAG, "MsgBoxOrientationEventListener.onOrientationChanged|orientation="+orientation);
			if (orientation > 314 || orientation < 45) {
				if (myCamera.CUR_CAMERA == myCamera.FRONT_CAMERA) {
					myCamera.setRotation(90);//录制窗口的角度
					glRender.setGlRotation(270);//播放窗口的角度
				} else if (myCamera.CUR_CAMERA == myCamera.BACK_CAMERA){
					myCamera.setRotation(0);//录制窗口的角度
					glRender.setGlRotation(90);//播放窗口的角度
				}
				mOrientation = 0;
			} else if (orientation > 44 && orientation < 135) {
				if (myCamera.CUR_CAMERA == myCamera.FRONT_CAMERA) {
					myCamera.setRotation(90);//录制窗口的角度
					glRender.setGlRotation(270);//播放窗口的角度
				} else if (myCamera.CUR_CAMERA == myCamera.BACK_CAMERA){
					myCamera.setRotation(0);//录制窗口的角度
					glRender.setGlRotation(90);//播放窗口的角度
				}
				mOrientation = 90;
			} else if (orientation > 134 && orientation < 225) {
				if (myCamera.CUR_CAMERA == myCamera.FRONT_CAMERA) {
					myCamera.setRotation(90);//录制窗口的角度
					glRender.setGlRotation(270);//播放窗口的角度
				} else if (myCamera.CUR_CAMERA == myCamera.BACK_CAMERA){
					myCamera.setRotation(0);//录制窗口的角度
					glRender.setGlRotation(90);//播放窗口的角度
				}
				mOrientation = 180;
			} else {
				if (myCamera.CUR_CAMERA == myCamera.FRONT_CAMERA) {
					myCamera.setRotation(90);//录制窗口的角度
					glRender.setGlRotation(270);//播放窗口的角度
				} else if (myCamera.CUR_CAMERA == myCamera.BACK_CAMERA){
					myCamera.setRotation(0);//录制窗口的角度
					glRender.setGlRotation(90);//播放窗口的角度
				}
				mOrientation = 270;
			}			
		}		
	}

	/**
	 * 注册屏幕方向监听器
	 */
	private void registerOrientationListener() {
		if (orientationListener == null) {
			orientationListener = new MsgBoxOrientationEventListener(this, SensorManager.SENSOR_DELAY_UI);
		}
	}
	
	/**
	 * 打开屏幕方向监听器
	 */
	public void startOrientationListener() {
		if (orientationListener != null) {
			orientationListener.enable();
		}
	}

	/**
	 * 关闭屏幕方向监听器
	 */
	public void stopOrientationListener() {
		if (orientationListener != null) {
			orientationListener.disable();
		}
	}
	
	
    @Override
	public void onClick(View v) {
    	switch(v.getId()){
	    	case R.id.button_stop:
	    		//通话结束，结束前需要发一条消息通知对方
	    		finish();
	    		break;
	    	case R.id.button_switch_camera:
	    		//切换前后镜头
	    		Runnable switchCamera = new SwitchCameraRunnable();
				myController.execute(switchCamera);
	    		break;
	    	case R.id.button_audio:
	    		//切换至语音聊天
	    		break;
	    	case R.id.button_video:
	    		//切换至视频聊天
	    		break;
	    	case R.id.button_pause_audio:
	    		//关闭声音
	    		myController.getMyAudioManager().setAudioInputMute(false);
	    		myController.getMyAudioManager().setAudioOutputMute(false);
	    		break;
	    	case R.id.button_resume_audio:
	    		//打开声音
	    		myController.getMyAudioManager().setAudioInputMute(true);
	    		myController.getMyAudioManager().setAudioOutputMute(true);
	    		break;
	    	default:
	    		break;
    	}
	}
    
	@Override
	protected void onDestroy() {
		super.onDestroy();
		//关闭视频
		if(myCamera!=null){
			myCamera.closeCamera();
		}
		//打开手机通话
		if(mAudioManager != null){
			mAudioManager.setSpeakerphoneOn(true);			
		}
		//停止播放声音
		if(myController!=null){
			myController.getMyAudioManager().StopAudio();
		}
		//取消注册广播接收器
		if(videoMsgReceiver != null){
			this.unregisterReceiver(videoMsgReceiver);
	    }
	}
}